from wordpress_xmlrpc import Client
from wordpress_xmlrpc.methods import posts
from wordpress_xmlrpc import WordPressPost
import jieba
import pymysql
from blog import conf
from redis import StrictRedis
import pika
import json


class WordpressSmart(object):
	def __init__(self):
		# 登录DB
		self.db = pymysql.connect(conf.DB_IP, conf.DB_USER, conf.DB_PASSWD, conf.DB_NAME)
		# 连接wordpress
		self.client = Client(conf.HOST, conf.USER, conf.PASSWD)
		# 连接redis
		self.redis_obj = StrictRedis(host=conf.REDIS_HOST, port=conf.REDIS_PORT)

	def clear_article(self):
		"""清除爬虫获取的重复文章, 已经不需要了, 有了增量爬虫"""
		# 获取游标
		cursor = self.db.cursor()

		# 清除重复的文章
		cursor.execute("CREATE TABLE my_tmp AS SELECT MIN(ID) AS col1 FROM wp_posts GROUP BY post_title;")
		cursor.execute("DELETE FROM wp_posts WHERE ID NOT IN (SELECT col1 FROM my_tmp);")
		cursor.execute("DROP TABLE my_tmp;")

		# 提交事务
		self.db.commit()

		# 关闭游标
		cursor.close()

		# 关闭数据库
		self.db.close()

	def send_article(self, article_dic):
		"""用于在wordpress发送文章"""
		title = ''.join(list(map(lambda s: s if s.isalnum() else '', article_dic['title'])))
		content = article_dic['content']

		# 创建新内容, 标题和文章
		new_post = WordPressPost()
		new_post.title = title
		new_post.content = content

		# 设置为已经发布的状态
		new_post.post_status = 'publish'

		# 设置分类和标签
		new_post.terms_names = {
			'category': ['hello_python'],
			'post_tag': list(jieba.cut(title, cut_all=False))
		}
		try:
			print("<{}>文章发送成功; 编号为{}".format(title, self.client.call(posts.NewPost(new_post))), )
		except Exception as e:
			print("<{}>文章发送失败; 错误原因为:{}".format(title, e))

	def get_detail(self):
		"""从redis中获取爬虫的数据"""
		detail_dic = self.redis_obj.hgetall('blog_detail')
		# 设置详细信息的过期时间
		self.redis_obj.expire('blog_detail', 600)
		# 作为一个生成器
		for title, content in detail_dic.items():
			yield {'title': title.decode(),  'content': content.decode()}

	def run(self):
		"""类的主函数"""
		# 获取每一个文章信息, 使用生成器的方式
		gen_atricle = self.get_detail()
		for article_dic in gen_atricle:
			# 发送文章
			# self.send_article(article_dic)
			print(article_dic['title'], '已经发送')


class WordpressMQSmart(object):
	def __init__(self):
		"""初始化MQ连接对象, wordpress对象"""
		# wordpress连接对象
		self.client = Client(conf.HOST, conf.USER, conf.PASSWD)

		# MQ对象, 创建通道, 指定接收队列
		parameters = pika.ConnectionParameters(conf.MQ_HOST)
		self.connection = pika.BlockingConnection(parameters)
		self.channel = self.connection.channel()
		self.channel.queue_declare(queue=conf.MQ_QUEUE)

	def send_detail(self, ch, method, properties, body):
		"""用于在wordpress发送文章"""
		# 获取mq的数据, 使用json反序列化后转成字典形式
		article_dic = json.loads(body)
		title = ''.join(list(map(lambda s: s if s.isalnum() else '', article_dic['title'])))
		content = article_dic['content']

		# 创建新内容, 标题和文章
		new_post = WordPressPost()
		new_post.title = title
		new_post.content = content

		# 设置为已经发布的状态
		new_post.post_status = 'publish'

		# 设置分类和标签
		new_post.terms_names = {
			'category': ['hello_python'],
			'post_tag': list(jieba.cut(title, cut_all=False))
		}
		try:
			print("<{}>文章发送成功; 编号为{}".format(title, self.client.call(posts.NewPost(new_post))), )
		except Exception as e:
			print("<{}>文章发送失败; 错误原因为:{}".format(title, e))

	def run(self):
		try:
			# 告诉rabbitmq使用callback来接收信息
			self.channel.basic_consume(
				queue=conf.MQ_QUEUE,
				on_message_callback=self.send_detail,
				auto_ack=True)
		except:
			pass

		# 开始接收信息，并进入阻塞状态，队列里有信息才会调用on_message_callback进行处理
		self.channel.start_consuming()


if __name__ == '__main__':
	# word_press = WordpressSmart()
	# word_press.run()
	wordpress_mq = WordpressMQSmart()
	wordpress_mq.run()